<?php

declare(strict_types=1);

namespace App\Listener;

use Hyperf\Event\Annotation\Listener;
use Hyperf\Validation\Contract\ValidatorFactoryInterface;
use Hyperf\Validation\Event\ValidatorFactoryResolved;
use Psr\Container\ContainerInterface;
use Hyperf\Event\Contract\ListenerInterface;

/**
 * @Listener
 */
class ValidatorFactoryResolvedListener implements ListenerInterface
{
    /**
     * @var ContainerInterface
     */
    private $container;

    public function __construct(ContainerInterface $container)
    {
        $this->container = $container;
    }

    public function listen(): array
    {
        return [
            ValidatorFactoryResolved::class
        ];
    }

    public function process(object $event)
    {
        /**  @var ValidatorFactoryInterface $validatorFactory */
        $validatorFactory = $event->validatorFactory;

        // 注册验证器
        $validatorFactory->extend('top_up_mantissa_limit', function ($attribute, $value, $parameters, $validator) {
            return $value % 10 > 0;
        }, '充值金额最后一位金额数字(分)不能为零');
        // 当创建一个自定义验证规则时，你可能有时候需要为错误信息定义自定义占位符
//        $validatorFactory->replacer('foo', function ($message, $attribute, $rule, $parameters) {
//            return str_replace(':foo', $attribute, $message);
//        });
    }
}
